﻿using Microsoft.Extensions.Logging;
using RotovapPlatform.Domain.Business.Machine.Enums;
using RotovapPlatform.Domain.Common;
using RotovapPlatform.Domain.Services.Devices;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace RotovapPlatform.Application.Services.Devices
{
	/// <summary>
	/// 设备应用服务实现
	/// 提供设备控制和状态管理的高级功能
	/// </summary>
	public class DeviceAppService : IDeviceAppService, IDisposable
	{
		private readonly IDeviceDomainService _deviceDomainService;
		private readonly ILogger<DeviceAppService> _logger;

		public event EventHandler<DeviceModeChangedEventArgs> DeviceModeChanged;
		public event EventHandler<DeviceStatusChangedEventArgs> DeviceStatusChanged;

		public DeviceAppService(
			IDeviceDomainService deviceDomainService,
			ILogger<DeviceAppService> logger)
		{
			_deviceDomainService = deviceDomainService ?? throw new ArgumentNullException(nameof(deviceDomainService));
			_logger = logger ?? throw new ArgumentNullException(nameof(logger));

			// 订阅领域服务的事件
			_deviceDomainService.DeviceModeChanged += OnDeviceDomainServiceModeChanged;
			_deviceDomainService.DeviceStatusChanged += OnDeviceDomainServiceStatusChanged;
		}

		/// <summary>
		/// 获取当前设备模式
		/// </summary>
		public Task<DeviceEnums.DeviceMode> GetCurrentDeviceModeAsync()
		{
			try
			{
				_logger.LogDebug("应用服务: 获取当前设备模式");
				return _deviceDomainService.GetCurrentDeviceModeAsync();
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "应用服务: 获取当前设备模式时发生错误");
				throw;
			}
		}

		/// <summary>
		/// 设置设备模式
		/// </summary>
		public async Task<OperationResult> SetDeviceModeAsync(DeviceEnums.DeviceMode mode)
		{
			try
			{
				_logger.LogInformation($"应用服务: 设置设备模式为: {mode}");
				return await _deviceDomainService.SetDeviceModeAsync(mode);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"应用服务: 设置设备模式为 {mode} 时发生错误");
				return new OperationResult { Success = false, Message = $"设置设备模式时发生错误: {ex.Message}" };
			}
		}

		/// <summary>
		/// 获取设备状态
		/// </summary>
		public Task<DeviceEnums.DeviceStatus> GetDeviceStatusAsync()
		{
			try
			{
				_logger.LogDebug("应用服务: 获取设备状态");
				return _deviceDomainService.GetDeviceStatusAsync();
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "应用服务: 获取设备状态时发生错误");
				throw;
			}
		}

		/// <summary>
		/// 执行紧急停止
		/// </summary>
		public async Task<OperationResult> ExecuteEmergencyStopAsync()
		{
			try
			{
				_logger.LogInformation("应用服务: 执行紧急停止");

				// 假设这里有紧急停止的实现
				await Task.Delay(100); // 模拟异步操作

				return new OperationResult { Success = true, Message = "紧急停止已执行" };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "应用服务: 执行紧急停止时发生错误");
				return new OperationResult { Success = false, Message = $"执行紧急停止时发生错误: {ex.Message}" };
			}
		}

		/// <summary>
		/// 重置设备
		/// </summary>
		public async Task<OperationResult> ResetDeviceAsync()
		{
			try
			{
				_logger.LogInformation("应用服务: 重置设备");

				// 假设这里有重置设备的实现
				await Task.Delay(100); // 模拟异步操作

				return new OperationResult { Success = true, Message = "设备已重置" };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "应用服务: 重置设备时发生错误");
				return new OperationResult { Success = false, Message = $"重置设备时发生错误: {ex.Message}" };
			}
		}

		/// <summary>
		/// 获取可用的设备模式列表
		/// </summary>
		public Task<DeviceEnums.DeviceMode[]> GetAvailableModesAsync()
		{
			try
			{
				_logger.LogInformation("应用服务: 获取可用的设备模式列表");
				return _deviceDomainService.GetAvailableModesAsync();
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "应用服务: 获取可用的设备模式列表时发生错误");
				throw;
			}
		}

		/// <summary>
		/// 检查指定模式是否可用
		/// </summary>
		public Task<bool> IsModeAvailableAsync(DeviceEnums.DeviceMode mode)
		{
			try
			{
				_logger.LogInformation($"应用服务: 检查设备模式 {mode} 是否可用");
				return _deviceDomainService.IsModeAvailableAsync(mode);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"应用服务: 检查设备模式 {mode} 是否可用时发生错误");
				throw;
			}
		}

		/// <summary>
		/// 开始监控设备状态
		/// </summary>
		public Task StartMonitoringAsync()
		{
			try
			{
				_logger.LogInformation("应用服务: 开始监控设备状态");
				return _deviceDomainService.StartMonitoringAsync();
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "应用服务: 开始监控设备状态时发生错误");
				throw;
			}
		}

		/// <summary>
		/// 停止监控设备状态
		/// </summary>
		public Task StopMonitoringAsync()
		{
			try
			{
				_logger.LogInformation("应用服务: 停止监控设备状态");
				return _deviceDomainService.StopMonitoringAsync();
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "应用服务: 停止监控设备状态时发生错误");
				throw;
			}
		}

		/// <summary>
		/// 处理领域服务的模式变更事件
		/// </summary>
		private void OnDeviceDomainServiceModeChanged(object sender, DeviceModeChangedEventArgs e)
		{
			try
			{
				_logger.LogInformation($"应用服务: 设备模式已变更为 {e.Mode}");
				DeviceModeChanged?.Invoke(this, e);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "应用服务: 处理设备模式变更事件时发生错误");
			}
		}

		/// <summary>
		/// 处理领域服务的状态变更事件
		/// </summary>
		private void OnDeviceDomainServiceStatusChanged(object sender, DeviceStatusChangedEventArgs e)
		{
			try
			{
				_logger.LogInformation($"应用服务: 设备状态已变更为 {e.Status}");
				DeviceStatusChanged?.Invoke(this, e);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "应用服务: 处理设备状态变更事件时发生错误");
			}
		}

		/// <summary>
		/// 释放资源
		/// </summary>
		public void Dispose()
		{
			// 取消事件订阅
			if (_deviceDomainService != null)
			{
				_deviceDomainService.DeviceModeChanged -= OnDeviceDomainServiceModeChanged;
				_deviceDomainService.DeviceStatusChanged -= OnDeviceDomainServiceStatusChanged;
			}
		}
	}
}